<?php
/**
 * TicketController
 *-------------------------
 *
 * Deal with menu display, selected status. Top menu - sub menu 
 *
 * PHP versions 5
 *
 * LICENSE: This source file is from Smarter Ver4.0, which is a comprehensive shopping engine
 * that helps consumers to make smarter buying decisions online. We empower consumers to compare
 * the attributes of over one million products in the computer and consumer electronics categories
 * and to read user product reviews in order to make informed purchase decisions. Consumers can then
 * research the latest promotional and pricing information on products listed at a wide selection of
 * online merchants, and read user reviews on those merchants.
 * The copyrights is reserved by http://www.mezimedia.com.
 * Copyright (c) 2005, Mezimedia. All rights reserved.
 *
 * @author     james.huang <james_huang@mezimedia.com>
 * @copyright  (C) 2004-2008 Mezimedia.com
 * @license    http://www.mezimedia.com  PHP License 5.2
 * @version    CVS: $Id: UserController.php
 * @link       http://pms.mezimedia.com/
 * @deprecated File deprecated in Release 1.0
 */
 
require_once 'Zend/Session/Namespace.php';

require_once('app/model/Ticket.php');

require_once('app/lib/Pager.php');

class TicketController extends Zend_Controller_Action
{
	public $task_item = 5; // each page item number
	
	function preDispatch()
	{		
		// Page menulist 
		$this->view->controller = $this->_request->getControllerName();
		$this->view->action = $this->_request->getActionName();
		$subMenu = array (
			'Ticket List' => array (
				'key' => 'index',
				'url' => '/ticket/',
				'selected' => false,
				'title' => 'Task list ...',	
			)
		);
		$menu = new Menu();
		$menuTree = $menu->renderMenu($this->_request->getControllerName(), $this->_request->getActionName(), $subMenu);
		$this->view->menuTree = $menuTree;

		// Page namespace
		$this->tns = new Zend_Session_Namespace('TT_Ticket');

		// Page useful url
		$this->view->base_url = '/ticket/';
		$this->view->this_url = $_SERVER['REQUEST_URI'];
//		$this->view->referer_url = $_SERVER['HTTP_REFERER'];
		$this->view->filter_url = $this->view->base_url.'filter';
		$this->view->search_url = $this->view->base_url.'search';
		$this->view->upload_url = $this->view->base_url.'upload/id/'.$this->_getParam('id');
		$this->view->create_url = ($this->tns->now_page > 1) ? $this->view->base_url.'new/p/'.$this->tns->now_page : $this->view->base_url.'new';
		$this->view->update_url = ($this->tns->now_page > 1) ? $this->view->base_url.'edit/p/'.$this->tns->now_page : $this->view->base_url.'edit';
		$this->view->page_url = ($this->tns->now_page > 1) ? $this->view->base_url.'index/p/'.$this->tns->now_page : $this->view->base_url;
		
		// Page module var
		$this->oTicket = new Ticket();
	}
	
    ///////////////////////////////////////////////////////////////////////////////////////////////
    // action controller method
	
	public function indexAction()
	{
		$this->ticketFilter();
		$this->buildTicketList();
	}

	public function newAction()
	{
		if ($this->_getParam('save')) {
			$data = Utils::db_mk_row_data($this->oTicket->getCols(), $this->_getAllParams());
			try {
				$this->oTicket->insert($data);
			}  catch (Exception $e) {
				$this->view->errors = array($e->getMessage());
			}
			$this->_redirect($this->view->page_url);
		}
		
		$this->view->entites = $this->oTicket->getEntities();
	}
	
	public function editAction()
	{
		$ticket_id = $this->_getParam('id') ? $this->_getParam('id') : 0;
		
		if ($this->_getParam('save')) {
			$data = Utils::db_mk_row_data($this->oTicket->getCols(), $this->_getAllParams());
			try {
				$this->oTicket->update($data, $ticket_id);
			}  catch (Exception $e) {
				print_r( array($e->getMessage()));
			}
			$this->_redirect($this->view->page_url);
		}
		
		$ticket_items = $this->oTicket->find($ticket_id)->toArray();
		
		$this->view->entites = $this->oTicket->getEntities();
		$this->view->ticket = $ticket_items[0];
	}
	
	public function filterAction()
	{
//		Utils::dumper($this->_getAllParams());
		$k = $this->_getParam('k');
		$v = $this->_getParam('v');
		if (strlen($k)> 0) {
			$this->tns->filter[$k] = $v;
		}
		echo 'success';
		exit;
	}
	
	public function uploadAction ()
    {
		$ticket_id = $this->_getParam('id') ? $this->_getParam('id') : 0;
		
		// deal with the attachment upload
		if ($this->_getParam('has_attachment')) {
	        if ($this->uploadAttachment('attachment_file', $ticket_id)) {
	        	$this->oTicket->update(array('attachment' => 1), $ticket_id);
	        }
		}
		
		// get attachment list
		$filelist = array();
		$filePath = __ROOT_PATH.'/data/tickets/'.$ticket_id;
		$httpPath = __ROOT_HOST.'/data/tickets/'.$ticket_id;
		if (file_exists($filePath)) {
			if ($handle = opendir($filePath)) {
				while ($file = readdir($handle)) {
					if ($file != "." && $file != ".." && $file != "Thumbs.db") {
						$path = $httpPath.'/'.$file;
						$icon = $this->getAttachmentIcon($file);
						array_push($filelist, array(
							'name'	=> $file,
							'icon'	=> $icon,
							'path'	=> $path,
						));
					}
				}
			}
			closedir($handle);
		}
		
		$this->view->filelist = $filelist;
    }
	
	public function searchAction() 
    {
        $this->_redirect('/'); 
    }
	
	public function noRouteAction() 
    {
        $this->_redirect('/'); 
    }
    
    ///////////////////////////////////////////////////////////////////////////////////////////////
    // index action support method

	public function ticketFilter () {
		if (!isset($this->tns->filter)) {
			$this->tns->filter = array(
				'title'			=> '',
				'status'		=> 0,
				'property_id'	=> 0,
				'requester_id'	=> 0,
				'replier_id'	=> 0,
			);
		}
		$this->oTicket->setFilter($this->tns->filter);
		// filter options
		$this->view->filter = $this->tns->filter;
//		Utils::dumper($this->view->filter);
	}
	
	public function buildTicketList () {
		$ticket_list = array();
		foreach ($this->oTicket->getTicketList() as $ticket) {
			$ticket['status']		= $this->oTicket->getEntityValue('status', $ticket['status']);
			$ticket['property']		= $this->oTicket->getEntityValue('property', $ticket['property_id']);
			$ticket['requester']	= $this->oTicket->getEntityValue('requester', $ticket['requester_id']);
			$ticket['replier']		= $this->oTicket->getEntityValue('manager', $ticket['replier_id']);
			$ticket['attach']		= ($ticket['attachment']) ? '<img src="/images/icon_attach.gif"/>' : '';
			$ticket['roadmap']		= ($ticket['ticket_type'] == 'roadmap') ? '<img src="/images/icon_yes.gif"/>' : '<img src="/images/icon_no.gif"/>';
			$ticket['onEdit']		= 'onclick="javascript:redirect(\'/ticket/edit/id/'.$ticket['id'].'/p/'.$this->tns->now_page.'\');"';
			$ticket['onReply']		= 'onclick="javascript:;"';
			array_push($ticket_list, $ticket);
		}
		$this->view->ticket_list = $ticket_list;
		$this->view->entites = $this->oTicket->getEntities();
	}
	
	public function uploadAttachment ($name, $id) {
		$uploadPath = __ROOT_PATH.'/data/tickets/'.$id;
		if (!file_exists($uploadPath)) @mkdir($uploadPath, 0777);
		$extensions = array ("jpg","png","gif","pdf","doc","xls");
		$_tempFile  = $_FILES[$name]['tmp_name'];
		$_realName  = $_FILES[$name]['name'];
		$_errormsg  = $_FILES[$name]['error'];
		$_extension = strtolower(str_replace(".", "", strrchr($_realName, ".")));
		if (in_array($_extension, $extensions) && is_uploaded_file($_tempFile) && $_errormsg == 0) {
			$target = $uploadPath.'/'.$_realName;
			if (move_uploaded_file($_tempFile, $target)) {
				@chmod($target, 0777);
				return true;
			}
		}
		return false;
	}
	
	public function getAttachmentIcon ($name) {
		$_extension = strtolower(str_replace(".", "", strrchr($name, ".")));
		switch ($_extension) {
			case 'pdf' :
			case 'doc' :
			case 'xls' :
			case 'rar' :
				return "<img src=\"/images/icon_{$_extension}.gif\" border=\"0\" />";
			default : 
				return "<img src=\"/images/icon_img.gif\" border=\"0\" />";
		}
		return "";
	}
}